<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
  </head>
  <body>
    <div id="app">
      <ul>
        <li><router-link to="/">Home</router-link></li>
        <li><router-link to="/post/1">/post/1</router-link></li>
        <li><router-link to="/post/2">/post/2</router-link></li>
      </ul>
      <router-view></router-view>
    </div>
    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router@3/dist/vue-router.js"></script>
    <script>
      function getPostById(postId) {
        return new Promise((resolve) => {
          setTimeout(() => {
            resolve({
              title: `标题${postId}`,
              content: `内容${postId}`,
            });
          }, 1000);
        });
      }
      const Home = { template: "<div>Home</div>" };
      const Post = {
        props: ["postId"],
        data: () => ({ post: null, error: null, loading: false }),
        created() {//在组件实例创建后调用fetchPost方法获取数据，并且保存到data上
          this.fetchPost();
        },
        watch: {//this.$route 代表路由匹配的结果
          $route: function(){//监听$route变化 ，当它发生变化后重新请求数据
            this.fetchPost();
          },
        },
        methods:{
          fetchPost(){
            this.post = this.error = null;
            this.loading = true;
            getPostById(this.postId)
              .then(
                (post) => {
                  this.post = post;
                },
                (error) => {
                  this.error = error;
                }
              )
              .finally(() => {
                this.loading = false;
              });
          }
        },
        template: `
        <div>
          <div v-if="loading">
            <p>loading......</p>
          </div>  
          <div v-if="error">
            <p>{{error.message}}</p>
          </div>  
          <div v-if="post">
            <p>{{post.title}}</p>
            <p>{{post.content}}</p>
          </div>  
        </div>
    `,
      };
      var routes = [
        { path: "/", component: Home },
        { path: "/post/:postId", component: Post, props: true },
      ];
      Vue.use(VueRouter);
      var router = new VueRouter({ routes });
      var vm = new Vue({
        el: "#app",
        router,
      });
    </script>
  </body>
</html>
